package com.haisen.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.haisen.core.utils.PageResultSet;
import com.haisen.dataobject.entity.VerifyCodeHist;
import com.haisen.dataobject.mapper.base.VerifyCodeHistMapper;
import com.haisen.dataobject.query.VerifyCodeHistQuery;
import com.haisen.service.VerifyCodeHistService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VerifyCodeHistServiceImpl implements VerifyCodeHistService{

    @Autowired
   private VerifyCodeHistMapper verifyCodeHistMapper;

    @Override
    public PageResultSet<VerifyCodeHist> findByPage(VerifyCodeHistQuery verifyCodeHistQuery) {

        if (!StringUtils.isEmpty(verifyCodeHistQuery.getOrderBy())){
            PageHelper.orderBy(verifyCodeHistQuery.getOrderBy());
        }
        PageHelper.offsetPage(verifyCodeHistQuery.getOffset(),verifyCodeHistQuery.getLimit());

        Weekend<VerifyCodeHist> example = Weekend.of(VerifyCodeHist.class);
        WeekendCriteria<VerifyCodeHist,Object> criteria = example.weekendCriteria();
        //todo:增加条件，默认只能看到自己的，管理员可以看到所有的
        List<String> ls = new ArrayList<>();
        ls.add("all");
        //一线员工只能看到通知和自己订阅的信息
        String username = (String) SecurityUtils.getSubject().getPrincipal();
            ls.add(username);

        if (!StringUtils.isEmpty(verifyCodeHistQuery.getSubscribe())){
            ls.clear();
            ls.add("all");ls.add(verifyCodeHistQuery.getSubscribe());
        }

        criteria.andIn(VerifyCodeHist::getSubscribe, ls);
         log.info("查询条件={}", JSON.toJSONString(ls));
        if (!StringUtils.isEmpty(verifyCodeHistQuery.getPublish())){
            criteria.andEqualTo(VerifyCodeHist::getPublish,verifyCodeHistQuery.getPublish());
        }

        example.setOrderByClause("id desc");

        PageResultSet<VerifyCodeHist> resultSet = new PageResultSet<>();
        resultSet.setRows(verifyCodeHistMapper.selectByExample(example));
        resultSet.setTotal(verifyCodeHistMapper.selectCountByExample(example));
        return resultSet;
    }
}
